package com.zb.kc.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zb.kc.entity.EduSubject;
import com.zb.kc.entity.excel.SubjectData;
import com.zb.kc.service.IEduSubjectService;
import com.zb.kc.servicebase.exceptionhandler.KgcException;

/**
 * 这个类就是用来读取excel的每一行内容，并且你自己可以
 * 自定义的去处理，我们这里需要把内容读出来，插入到数据
 * 库中，问题就是这个类不是spring管理的，就不能够使用自动注入，
 * 所以我们这里自己在构造方法里赋值即可
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private IEduSubjectService subjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(IEduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if (data == null) {
            throw new KgcException(50000, "文件数据为空");
        }

        // 一行行的读取,添加一级分类
        EduSubject subjectOne = findOneSubject(data.getOneSubjectName());
        // 假如一级分类不存在才添加，并且返回该一级分类的pid
        if (subjectOne == null) {
            subjectOne = new EduSubject();
            subjectOne.setParentId("0");
            subjectOne.setTitle(data.getOneSubjectName());
            subjectService.save(subjectOne);
        }
        // 添加二级分类
        EduSubject subjectTwo = findTwoSubject(data.getTwoSubjectName(), subjectOne.getId());
        if (subjectTwo == null) {
            subjectTwo = new EduSubject();
            subjectTwo.setParentId(subjectOne.getId());
            subjectTwo.setTitle(data.getTwoSubjectName());
            subjectService.save(subjectTwo);
        }
    }

    // 判断数据库中是否已经存在一级分类
    private EduSubject findOneSubject(String name) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        return subjectService.getOne(wrapper);
    }

    /**
     * 判断是否存在二级分类，不存在返回true
     *
     * @param name
     * @param pid
     * @return
     */
    private EduSubject findTwoSubject(String name, String pid) {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        return subjectService.getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
